//
//  LXDBManager.m
//  kdxf_test
//
//  Created by iOS-01 on 16/11/3.
//  Copyright © 2016年 iOS-01. All rights reserved.
//

#import "LXDBManager.h"
#import "FMDB.h"
#import "FMDatabase.h"

@implementation LXDBManager

{
    FMDatabase *fmdb;
}

+ (LXDBManager *)sharedManager {
    static LXDBManager *manager = nil;
    @synchronized (self) {
        if (manager == nil) {
            manager = [[LXDBManager alloc] init];
        }
    }
    return manager;
}

- (instancetype)init {
    if (self = [super init]) {
        [self createDatabase];
    }
    return self;
}

- (void)createDatabase {
    //[注意]数据库存在沙盒路径下，数据库的后缀名：.db或者.sqlite
    //1.找到沙盒路径  数据库存放的沙盒路径的Documents文件夹下
    NSString *path = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/UserDB.db"];
    NSLog(@"%@",path);
    
    //2.打开数据库
    //数据库在使用之前必须要打开
    fmdb = [[FMDatabase alloc]initWithPath:path];
    BOOL isOpen = [fmdb open];
    //判断数据库是否打开成功
    if (isOpen) {
        NSLog(@"数据库打开成功");
        //3.创建表格的sql语句
        NSString *sql = @"create table if not exists Person (ID integer primary key autoincrement,name varchar(256),age ingeter,image blob)";
        //blob表示二进制
        
        //4.开始创建表格
        BOOL isSuccess = [fmdb executeUpdate:sql];
        //[注意]使用fmdb数据持久性存储 除了查询功能 创建表格、增、删、改操作 都调用相同方法executeUpdate：
        if (isSuccess) {
            NSLog(@"表格创建成功");
        }else{
            NSLog(@"表格失败原因：%@",fmdb.lastErrorMessage);
        }
        
        
    }else{
        NSLog(@"失败原因:%@",fmdb.lastErrorMessage);
    }
}

- (BOOL)isExists:(NSString *)userName {
    NSString *sql = @"select * from user where userName = ?";
    FMResultSet *rs = [fmdb executeQuery:sql, userName];
    if ([rs next]) {
        return YES;
    }
    return NO;
}

- (void)addUserModel:(LXUserModel *)model {
    BOOL isExists = [self isExists:model.name];
    if (isExists) {
        NSLog(@"is exists");
        return;
    }
    //1.向数据库中插入内容
    NSString *sql = @"insert into Person(name,age,image) values (?,?,?)";
    //?表示占位符
    NSString *name = @"张三";
    //数据库中不能存放基本类型的数据 必须用基本类型的数据转化成oc的对象
    NSNumber *age = [NSNumber numberWithInt:30];
    
    UIImage *image = [UIImage imageNamed:@"1.jpg"];
    //将图片转化成二进制  UIImagePNGRepresentation无论是png还是jpg的图片都可以使用该方法转化成nsdata
    NSData *imageData = UIImagePNGRepresentation(image);
    
    //2.插入数据
    BOOL isSuccess = [fmdb executeUpdate:sql,name,age,imageData];
    if (isSuccess) {
        NSLog(@"插入数据成功");
    }else{
        NSLog(@"插入数据失败%@",fmdb.lastErrorMessage);
    }
    
    //在相同路径下 如果存在同名数据库 那么创建就不会成功 而是直接打开
    //同理 表格也一样 相同路径下不会重复创建同名的表格
}

- (LXUserModel *)searchAllUsers {
//    NSString *selectSql = @"select * from user";
//    FMResultSet *rs = [_dataBase executeQuery:selectSql];
//    NSMutableArray *array = [NSMutableArray array];
//    while ([rs next]) {
//        LXUserModel *model = [[LXUserModel alloc] init];
//        model.name = [rs stringForColumn:@"name"];
//        model.age = [rs intForColumn:@"age"];
//        
//        NSData *data = [rs dataForColumn:@"image"];
//        model.image = [UIImage imageWithData:data];
//        [array addObject:model];
//    }
    //1.创建sql语句
    NSString *sql = @"select * from Person where name = ?";
    
    //2.查询
    FMResultSet *result = [fmdb executeQuery:sql,@"张三"];
    LXUserModel *model = [[LXUserModel alloc] init];
    if ([result next]) {
        NSString *name = [result stringForColumn:@"name"];
        int age = [result intForColumn:@"age"];
        
        NSData *imageData = [result dataForColumn:@"image"];
        
        model.name = name;
        model.age = [NSString stringWithFormat:@"%d",age];
        model.image = [UIImage imageWithData:imageData];
    }else{
        model.name = @"";
        model.age = @"";
        model.image = nil;
    }

    return model;
}

- (void)deleteUserModelWithUserId:(int)userId {
    //1.
    NSString *sql = @"delete from Person where name = ?";
    BOOL isSuccess = [fmdb executeUpdate:sql,@"张三"];
    if (isSuccess) {
        NSLog(@"删除成功");
    }else{
        NSLog(@"删除失败原因：%@",fmdb.lastErrorMessage);
    }
}

- (void)updateUserModel:(LXUserModel *)model userId:(int)userId {
    //1.创建sql语句
    NSString *sql = @"update Person set age = ?,image = ? where name = ?";
    
    //2.开始修改
    UIImage *image = [UIImage imageNamed:@"2.jpg"];
    NSData *imageData = UIImagePNGRepresentation(image);
    BOOL isSuccess = [fmdb executeUpdate:sql,@(20),imageData,@"张三"];
    if (isSuccess) {
        NSLog(@"修改成功");
    }else{
        NSLog(@"失败原因：%@",fmdb.lastErrorMessage);
    }
}

@end
